import { useEffect, useState } from 'react'

import StorageUtil, { ACCESS_TOKEN_KEY } from '../utils/StorageUtil'

export function useAuth() {
  const [accessToken, setAccessToken] = useState('')
  const [loading, setLoading] = useState(true)
  console.log('useAuth accessToken', accessToken)

  const getAccessToken = async () => {
    const token = await StorageUtil.getItem(ACCESS_TOKEN_KEY)
    setLoading(false)
    setAccessToken(token)
  }

  useEffect(() => {
    getAccessToken()
  }, [])

  const login = (token: string) => {
    StorageUtil.setItem(ACCESS_TOKEN_KEY, token)
    setAccessToken(token)
  }

  const logout = () => {
    setAccessToken('')
  }

  return { loading, accessToken, login, logout }
}
